package kmitl.comsci.bustacker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class SuggestionActivity extends Activity{

	private Spinner suggestSpinner; 
	private TextView suggestTextView;
	
	private HttpPost httppost;
    private HttpClient httpclient;
    private List<NameValuePair> nameValuePairs;
    
    private String broute = null;;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.suggestion);
		setSuggestionSpinner();
		setButton();
		setSuggestionMsg();
	}
	
	private void setButton() {
		Button sendButton = (Button) findViewById(R.id.suggestion_sendButton);
		sendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendMsg(broute);
				clearAllText();
			}
		});
		
		Button backButton = (Button) findViewById(R.id.suggestion_backButton);
		backButton.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SuggestionActivity.this, HomeActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	

	private void clearAllText() {
		suggestTextView.setText("");
	}
	
	//set Spinner
	private void setSuggestionSpinner() {
		
		suggestSpinner = (Spinner)findViewById(R.id.select_FirstLocation);
		JSONObject jObject = initTextList();
		
		List<String> arrList = new ArrayList<String>();
		try {
			arrList = getDataFromJson(jObject);
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
		ArrayAdapter<String> arrAd = new ArrayAdapter<String>(SuggestionActivity.this,
				android.R.layout.simple_spinner_item, 
				arrList);
		
		suggestSpinner.setAdapter(arrAd);
		
		
		suggestSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        Object item = parent.getItemAtPosition(pos);
		        broute = item.toString();
		       
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    	//someting
		    }
		});
		
	}
	private void setSuggestionMsg() {
		suggestTextView = (TextView)findViewById(R.id.suggestion_editText2);
		
		
	}
	@SuppressLint("SimpleDateFormat")
	private void sendMsg(String bus_route_id) {
		
		if(!suggestTextView.getText().toString().equals("")) {
			
			try {
				StrictMode.ThreadPolicy policy = new
						StrictMode.ThreadPolicy.Builder()
						.permitAll().build();
						StrictMode.setThreadPolicy(policy);
			   		
				//date
				Calendar c = Calendar.getInstance();
			    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			    SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
			    String msg_date = df.format(c.getTime());
			    String msg_time = tf.format(c.getTime());
				
			    String msg_detail = suggestTextView.getText().toString();
			    
			    nameValuePairs.add(new BasicNameValuePair("check","true"));
				nameValuePairs.add(new BasicNameValuePair("bus_route_id" ,bus_route_id));
				nameValuePairs.add(new BasicNameValuePair("msg_date" ,msg_date));
				nameValuePairs.add(new BasicNameValuePair("msg_time" ,msg_time));
				nameValuePairs.add(new BasicNameValuePair("msg_detail" ,msg_detail));
				
				HttpClient httpclient = new DefaultHttpClient();
				
				HttpPost httppost = new HttpPost("http://161.246.13.242/itone/php_set_msg.php");
			
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			
				httpclient.execute(httppost);
			}
			catch(Exception e){
	    		Log.d("log_err", "Error in http connection " + e.toString());
	    	}	
			
		}
		else {
			suggestTextView.setText("ERROR");
		}
		
	}
	private JSONObject initTextList() {
		//--StrictMode
		StrictMode.ThreadPolicy policy = new
				StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
				StrictMode.setThreadPolicy(policy);
	    
		//---connect to server	
		httpclient 		= new DefaultHttpClient();
		httppost 		= new HttpPost("http://161.246.13.242/itone/php_get_route.php");
		nameValuePairs  = new ArrayList<NameValuePair>();
		
		//-------------------------------------------------------------
		InputStream is = null;
        String result = null;
        JSONObject jsObj = null;
       
        try {
            
            httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
 
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
 
            is.close();
            result = sb.toString();
            
        
        } catch (ClientProtocolException e) {
            Log.e("ConnectServer", e.toString());
        } catch (IOException e) {
            Log.e("ConnectServer", e.toString());
        }
        try {
			jsObj =  new JSONObject(result);
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
        return jsObj;
	}
	public ArrayList<String> getDataFromJson(JSONObject jsonObject)throws IllegalStateException,IOException, JSONException, NoSuchAlgorithmException 
	{
		ArrayList<String> busRoute = new ArrayList<String>();
		JSONArray array = jsonObject.getJSONArray("Location Data");		 
		 	 
		
		if(array!=null)
	    {	
			 
			 for(int i = 0; i<array.length(); i++) 
			 {
					busRoute.add(array.getJSONObject(i).getString("bus_route"));
			 }
			 	
	      }
		
		return busRoute;
				
	}
}
